package com.ty.cloudpicture.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ty.cloudpicture.common.ErrorCode;
import com.ty.cloudpicture.common.UserConstant;
import com.ty.cloudpicture.exception.BusinessException;
import com.ty.cloudpicture.exception.ThrowUtils;
import com.ty.cloudpicture.manager.auth.StpKit;
import com.ty.cloudpicture.model.dto.user.UserQueryRequest;
import com.ty.cloudpicture.model.entity.User;
import com.ty.cloudpicture.model.enums.UserRoleEnum;
import com.ty.cloudpicture.model.vo.UserVO;
import com.ty.cloudpicture.service.UserService;
import com.ty.cloudpicture.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author ong char
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2025-02-09 22:57:22
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    /**
     * 用户注册
     * @param userAccount
     * @param userPassword
     * @param checkPassword
     * @return
     */
    @Override
    public long register(String userAccount, String userPassword, String checkPassword) {
        //校验数据
        if (StrUtil.hasBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //检查账户是否合法
        if (userAccount.length() < 4 || userAccount.length() > 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号长度不合法");
        }
        //检验密码是否合法
        if (userPassword.length() < 8 || userPassword.length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码长度不合法");
        }
        //检验两次密码是否一致
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }
        //检查账户是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count = this.count(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号重复");
        }
        String encryptPassword = this.encryptPassword(userPassword);
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        user.setCreateTime(new Date());
        boolean save = this.save(user);
        if (!save){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"注册失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     * @param userAccount
     * @param userPassword
     * @param request
     * @return
     */
    @Override
    public User login(String userAccount, String userPassword, HttpServletRequest request) {
        //校验数据
        if (StrUtil.hasBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        //密码加密
        userPassword = DigestUtil.md5Hex(userPassword);
        queryWrapper.eq("userPassword",userPassword);
        User user = this.getOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户不存在或密码错误");
        }
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,user);
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(UserConstant.USER_LOGIN_STATE,user);
        return user;
    }

    /**
     * 获取当前用户
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser= (User) userObj;
        ThrowUtils.throwIf(currentUser == null,ErrorCode.NOT_LOGIN_ERROR,"未登录");
        Long currentUserId = currentUser.getId();
        ThrowUtils.throwIf(currentUser == null || currentUserId == null,ErrorCode.NOT_LOGIN_ERROR);
        currentUser = this.getById(currentUserId);
        ThrowUtils.throwIf(currentUser == null,ErrorCode.NOT_LOGIN_ERROR);
        return currentUser;
    }

    /**
     * 用户信息脱敏
     * @param user
     * @return
     */
    @Override
    public UserVO getUserVO(User user) {
        ThrowUtils.throwIf(user == null,ErrorCode.NOT_LOGIN_ERROR);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求为空");
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public String encryptPassword(String password) {
        if (StrUtil.isBlank(password)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码为空");
        }
        return DigestUtil.md5Hex(password);
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (userList == null){
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public boolean updateUserInfo(User loginUser, User updateUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null || updateUser == null, ErrorCode.PARAMS_ERROR, "参数为空");
        
        // 创建要更新的用户对象
        User user = new User();
        user.setId(loginUser.getId());  // 使用登录用户的ID
        
        // 更新昵称
        if (StrUtil.isNotBlank(updateUser.getUserName())) {
            user.setUserName(updateUser.getUserName());
        }
        
        // 更新头像
        if (StrUtil.isNotBlank(updateUser.getUserAvatar())) {
            user.setUserAvatar(updateUser.getUserAvatar());
        }
        
        // 更新简介
        if (StrUtil.isNotBlank(updateUser.getUserProfile())) {
            user.setUserProfile(updateUser.getUserProfile());
        }
        
        user.setUpdateTime(new Date());
        return this.updateById(user);
    }

    @Override
    public boolean addUser(User user) {
        if (user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //检查账户是否存在
        if (this.getOne(new QueryWrapper<User>().eq("userAccount",user.getUserAccount()))!=null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户已存在");
        }
        return true;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

}




